package org.xhy.quickstarter.authority.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xhy.quickstarter.authority.entity.User;
import org.xhy.quickstarter.authority.service.UserService;
import org.xhy.quickstarter.authority.utils.JwtUtils;
import org.xhy.quickstarter.authority.utils.R;

import java.util.HashMap;

/**
 * Author: Xhy
 * CreateTime: 2022-06-04 12:04
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;


    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @PostMapping("/login")
    public R login(String name, String password){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        User user = userService.getOne(wrapper.eq(User::getName, name));
        if (ObjectUtils.isEmpty(user)) return R.error().message("没有该账号");

        if (!user.getPassword().equals(password)) return R.error().message("密码不一致");

        // 登录成功，生成token
        String token = JwtUtils.getJwtToken(String.valueOf(user.getId()), user.getName());

        return R.ok().data(new HashMap<String,Object>(){{
            put("token",token);
            put("name",name);
        }});
    }
}
